package config

import (
	"fmt"
	"path"
	"runtime"
	"strings"

	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

const (
	TimeFormat string = "2006-01-02 15:04:05"
)

var (
	Port       string
	LogLevel   string
	JwtSignKey string
	JwtExpTime int64 //过期时间单位为分钟
	UserName   string
	PassWord   string
)

// 定义返回数据规范
type ReponseData struct {
	Status  int                    `json:status`
	Message string                 `json:message`
	Data    map[string]interface{} `json:data`
}

// 构造函数
func NewReponseData() ReponseData {
	return ReponseData{
		200,
		"",
		nil,
	}
}

func initloglevel(logLevel string) {
	if logLevel == "debug" {
		logrus.SetLevel(logrus.DebugLevel)
	}
	if logLevel == "info" {
		logrus.SetLevel(logrus.InfoLevel)
	}
	if logLevel == "warning" {
		logrus.SetLevel(logrus.WarnLevel)
	}
	if logLevel == "error" {
		logrus.SetLevel(logrus.ErrorLevel)
	}
	logrus.SetReportCaller(true)
	//logrus.SetFormatter(&logrus.JSONFormatter{TimestampFormat: TimeFormat})
	logrus.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: TimeFormat,
		CallerPrettyfier: func(f *runtime.Frame) (function string, file string) {
			//frame是一个帧，可用于获取调用者PC值的函数，文件或行信息
			fileName := path.Base(f.File)
			return f.Function, fileName
		},
	})
}

func init() {
	//环境变量加载程序配置
	viper.SetDefault("LOG_LEVEL", "debug")
	viper.SetDefault("PORT", ":80")
	viper.SetDefault("JWT_SIGN_KEY", "lutongli")
	viper.SetDefault("JWT_EXPTIME", 1440)
	viper.SetDefault("USERNAME", "LUTONGLI")
	viper.SetDefault("PASSWORD", "LUTONGLI")
	//将与系统变量合并，重名的会覆盖
	viper.AutomaticEnv()
	LogLevel = viper.GetString("LOG_LEVEL")
	initloglevel(LogLevel)
	Port = viper.GetString("PORT")
	if ok := strings.HasPrefix(Port, ":"); !ok {
		//Port = ":" + Port
		Port = fmt.Sprintf("%s%s", ":", Port)
	}
	JwtSignKey = viper.GetString("JWT_SIGN_KEY")
	JwtExpTime = viper.GetInt64("JWT_EXPTIME")
	UserName = viper.GetString("USERNAME")
	PassWord = viper.GetString("PASSWORD")
}
